package com.nash.demands;

import java.util.Map;

import org.ksoap2.serialization.SoapObject;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.provider.BaseColumns;
import android.provider.Settings.Secure;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;

public class SendThread extends Thread {
  Handler mHandler;

  public Map<String, Integer> aSeverVersions;

  final static int STATE_DONE = 0;
  final static int STATE_RUNNING = 1;

  int mState;
  DemandsActivity app;

  SendThread(Handler h, DemandsActivity act) {
    mHandler = h;
    app = act;
  }

  @Override
  public void run() {
    mState = STATE_RUNNING;
    Message msg;
    try {

      int ret=sendOrders();

      msg = mHandler.obtainMessage();
      msg.arg1 = -1;
      msg.arg2 = DemandsActivity.SEND_STAGE_FINISH;
      msg.what=ret;
      mHandler.sendMessage(msg);
    } catch (Exception e3) {
      Log.e("ERROR", "Exception");
      msg = mHandler.obtainMessage();
      msg.arg1 = -1;
      msg.arg2 = DemandsActivity.SEND_ERROR;
      mHandler.sendMessage(msg);
    }
  }

  public void setState(int state) {
    mState = state;
  }

  private int sendOrders() throws DemandsException {
    Message msg;
    String sql = "select " + BaseColumns._ID + " as id, " + Helper.TBL_DEMAND_ID_AGENT + " as id_agent" + ", " + Helper.TBL_DEMAND_DATE + " as date, " + Helper.TBL_DEMAND_DEMAND_DATE + " as demandDate, "
        + Helper.TBL_DEMAND_ID_HOST + " as id_host ," + Helper.TBL_DEMAND_ID_OSNR + " as id_osnr, " + Helper.TBL_DEMAND_TS + " as create_ts, " + Helper.TBL_DEMAND_INFO + " as info " + " from " + Helper.TBL_DEMAND
        + " d where " + Helper.TBL_DEMAND_ADDIT + "=0 order by " + BaseColumns._ID;
    Cursor data = DemandsActivity.db.rawQuery(sql, null);
    int cnt = data.getCount();
    msg = mHandler.obtainMessage();
    msg.arg1 = 0;
    msg.arg2 = DemandsActivity.SEND_STAGE_ORDERS * 100000 + cnt;
    mHandler.sendMessage(msg);
    int error=0;
    int success=0;
    if (data.moveToFirst()) {
      int i = 1;
      int date_index = data.getColumnIndex("date");
      int ddate_index = data.getColumnIndex("demandDate");
      int agent_index = data.getColumnIndex("id_agent");
      int host_index = data.getColumnIndex("id_host");
      int osnr_index = data.getColumnIndex("id_osnr");
      int ts_insert_index = data.getColumnIndex("create_ts");
      int info_index = data.getColumnIndex("info");
      do {
        SoapObject obj = new SoapObject("http://demands.dostavka-m.ru/", "orders");
        long idDemand = data.getLong(0);
        SoapObject demand = new SoapObject("http://demands.dostavka-m.ru/", "demand");

        obj.addSoapObject(demand);
        demand.addProperty("id", idDemand);
        demand.addProperty("date", data.getString(date_index));
        demand.addProperty("demand_date", data.getString(ddate_index));
        demand.addProperty("id_agent", data.getInt(agent_index));
        demand.addProperty("date_insert", data.getString(ts_insert_index));
        // demand.addProperty("date_modification", "2011-09-04");
        demand.addProperty("id_host", data.getInt(host_index));
        demand.addProperty("id_osnr", data.getInt(osnr_index));
        String sInfo = data.getString(info_index);
        if (sInfo != null && !sInfo.trim().equals("")) {
          demand.addProperty("info", sInfo);
        }

        String sql_lines = "select " + BaseColumns._ID + " as id, " + Helper.TBL_DEMAND_LINE_AMOUNT + " as amount," + Helper.TBL_DEMAND_LINE_ID_TU + " as id_tu, " + Helper.TBL_DEMAND_LINE_PRICE + " as price from "
            + Helper.TBL_DEMAND_LINE + " dl where " + Helper.TBL_DEMAND_LINE_ID_DEMAND + "=" + idDemand;
        Cursor data_lines = DemandsActivity.db.rawQuery(sql_lines, null);

        int amount_index = data_lines.getColumnIndex("amount");
        int tu_index = data_lines.getColumnIndex("id_tu");
        int price_index = data_lines.getColumnIndex("price");

        if (data_lines.moveToFirst()) {
          do {
            SoapObject line = new SoapObject("http://demands.dostavka-m.ru/", "line");
            line.addProperty("id", data_lines.getInt(0));
            line.addProperty("amount", data_lines.getInt(amount_index));
            line.addProperty("id_tu", data_lines.getInt(tu_index));
            line.addProperty("price", "" + data_lines.getFloat(price_index));
            demand.addSoapObject(line);
          } while (data_lines.moveToNext());
          data_lines.close();
        }
        // demand.addSoapObject(line);
        try {
          app.transport.LoadBySoap("sendOrders", 0, Secure.getString(app.getContentResolver(), Secure.ANDROID_ID), app.getLicenseId(), app.getUserId(), obj);
          ContentValues cv = new ContentValues();
          cv.put(BaseColumns._ID, data.getLong(0));
          cv.put(Helper.TBL_DEMAND_ADDIT, 1);
          DemandsActivity.db.update(Helper.TBL_DEMAND, cv, BaseColumns._ID + "=?", new String[] { String.valueOf(data.getLong(0)) });// .update(Helper.TBL_DEMAND,
          success++;
        } catch (DemandsException e) {
          error++;
        }

        msg = mHandler.obtainMessage();
        msg.arg1 = i;
        msg.arg2 = DemandsActivity.SEND_STAGE_ORDERS * 100000 + cnt;
        mHandler.sendMessage(msg);

        i++;
      } while (data.moveToNext());

    }
    data.close();
    return (success<<8 | error);
  }
}
